# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
from collections import defaultdict
from pathlib import Path

import numpy as np
import torch
from PIL import Image


def load_json_file(file_path: Path):
    with open(file_path, "r") as f:
        data = json.load(f)
    return data


def convert_img2tensor(image_path):
    image_data = Image.open(image_path).convert("RGB")
    image_tensor = torch.from_numpy(np.array(image_data)).permute(2, 0, 1)
    return image_tensor


def reorganize_data(data):
    """
    data: a list of dicts, each dict like:
        {
          "prompt": <string>,
          "images": {
            "modelA": <path1>,
            "modelB": <path2>,
            ...
          }
        }
    returns: dict of model_name -> list of { "prompt": <>, "image": <> }
    """
    model_dict = defaultdict(list)

    for item in data:
        prompt = item["prompt"]
        for model_name, image_path in item["images"].items():
            model_dict[model_name].append({"prompt": prompt, "image": image_path})

    return dict(model_dict)
